<script setup>
import api from '../api/user_activity_api.js'  // 用户活动接口路径
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'
// 引入 ECharts 组件和所需模块
import * as echarts from 'echarts'
import VChart from 'vue-echarts'

// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
})
// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);
// 图表相关数据
const chartVisible = ref(false);
const chartData = ref([]);
const chartOption = ref({});

const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  action_type: ''  // 保留操作类型查询条件
});

const obj = ref({});

// 操作类型选项（仅选项值和显示为英文）
const actionTypeOptions = [
  { label: 'browse', value: 'browse' },
  { label: 'search', value: 'search' },
  { label: 'share', value: 'share' },
  { label: 'click', value: 'click' }
];

// 查询方法
const search = async () => {
  const result = await api.pageWithDetails(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

// 获取图表数据
const loadChartData = async () => {
  try {
    // 这里可以调用实际的API获取图表数据
    // 暂时使用模拟数据展示效果
    const actionTypeCount = {};

    // 计算每种操作类型的数量
    tableData.value.forEach(item => {
      const type = item.action_type;
      actionTypeCount[type] = (actionTypeCount[type] || 0) + 1;
    });

    const labels = Object.keys(actionTypeCount);
    const counts = Object.values(actionTypeCount);

    chartData.value = labels.map((label, index) => ({
      name: label,
      value: counts[index]
    }));

    // 设置图表选项
    chartOption.value = {
      title: {
        text: '用户活动类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '活动类型',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: chartData.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    chartVisible.value = true;
  } catch (error) {
    console.error('加载图表数据失败:', error);
  }
};

onMounted(async () => {
  await search();
  // 移除自动加载图表数据
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
  // 只有在图表已显示的情况下才重新加载图表数据
  if (chartVisible.value) {
    loadChartData();
  }
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};

const handleAdd = () => {
  obj.value = {
    user_id: '',
    action_type: '',
    action_detail: ''
  };
  editWinVisible.value = true;
};

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该用户活动记录吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
        // 只有在图表已显示的情况下才重新加载图表数据
        if (chartVisible.value) {
          loadChartData();
        }
      })
      .catch(() => {});
};
// 判断是否为管理员登录
const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
</script>

<template>
  <div class="user-activity-management-container">
    <!-- 查询表单（保留操作类型查询） -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="操作类型">
        <el-select v-model="searchObj.action_type" placeholder="请选择操作类型" clearable style="width: 200px;">
          <el-option
              v-for="option in actionTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item v-if="!isAdminLogin()">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="loadChartData">显示图表</el-button>
      </el-form-item>
    </el-form>

    <!-- 图表区域 -->
    <div v-if="chartVisible" class="chart-container">
      <v-chart class="chart" :option="chartOption" :autoresize="true" />
    </div>

    <!-- 用户活动表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
<!--      <el-table-column label="ID" width="80" align="center">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.id }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="用户" min-width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="操作类型" min-width="150">
        <template #default="scope">
          <el-tag :type="scope.row.action_type === 'favorite' ? 'success' :
                   scope.row.action_type === 'review' ? 'warning' : 'info'">
            {{ scope.row.action_type }}  <!-- 显示英文操作类型 -->
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作详情" min-width="300">
        <template #default="scope">
          {{ scope.row.action_detail }}
        </template>
      </el-table-column>
      <el-table-column  label="操作" min-width="180" align="center">
        <template #default="scope">
<!--          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑用户活动记录" width="600px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
<!--        <el-form-item label="用户ID" required>-->
<!--          <el-input v-model="obj.user_id" autocomplete="off" placeholder="请输入用户ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="操作类型" required>
          <el-select v-model="obj.action_type" placeholder="请选择操作类型">
            <el-option
                v-for="option in actionTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作详情" required>
          <el-input
              type="textarea"
              v-model="obj.action_detail"
              autocomplete="off"
              rows="4"
              placeholder="请输入详细操作内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.chart-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart {
  height: 400px;
  width: 100%;
}
</style>
